//
//  MJTComposeTextView.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/19.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit

class MJTComposeTextView: UITextView {

    // 站位label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "听说👂下雨天☔️,音乐🎵和薯条🍟更配(⊙o⊙)哦..."
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    //外界设置站位文字
    var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    //重写font
    override var font: UIFont? {
        didSet {
            placeHolderLabel.font = font
        }
    }
    //重写text
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加控件设置约束
    private func setupUI() {
        // 监听文字改变textChange
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        addSubview(placeHolderLabel)
        // 使用系统约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false

        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: -8))
    }
    // 监听文字改变
    @objc private func textChange() {
        placeHolderLabel.hidden = hasText()
    }
    //关闭通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
